package com.blank.shop.security.handler;

import com.blank.shop.security.config.BlankShopProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * <br/>Date 2021/9/10
 * <br/>Time 0:15:58
 *
 * @author _blank
 */
@Slf4j
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private ObjectMapper jacksonObjectMapper;

    private final BlankShopProperties blankShopProperties;

    public MyAuthenticationFailureHandler(BlankShopProperties blankShopProperties) {
        this.blankShopProperties = blankShopProperties;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败！");

        if (Objects.equals(BlankShopProperties.LoginType.JSON, this.blankShopProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);

            final ImmutableMap<String, String> content = ImmutableMap.of("content", exception.getMessage());
            response.getWriter().write(this.jacksonObjectMapper.writeValueAsString(content));
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }

}
